package com.ldq.imooc.basics.multiThread;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Scanner;

/**
 * @Author : 第五若雪
 * @Description :
 * @Date : 2018/4/24 13:43
 * @Modified by :
 */

class DaemonThread implements Runnable {

    private void writeToFile() throws Exception {
        File file = new File("F:" + File.separator + "daemon.txt");
        OutputStream os = new FileOutputStream(file, true);
        int count = 0;
        while (count < 99) {
            os.write(("\r\nworld" + count).getBytes());
            System.out.println("守护线程" + Thread.currentThread().getName() + "向文件中写入了world" + count++);
            Thread.sleep(1000);
        }

    }

    @Override
    public void run() {

        System.out.println("进入守护线程：" + Thread.currentThread().getName());
        try {
            writeToFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("退出守护线程：" + Thread.currentThread().getName());
    }
}

public class DaemonThreadDemo {

    public static void main(String[] args) {

        System.out.println("进入主线程：" + Thread.currentThread().getName());
        DaemonThread daemonThread = new DaemonThread();
        Thread thread = new Thread(daemonThread);
        thread.setDaemon(true);
        thread.start();

        Scanner scanner = new Scanner(System.in);
        scanner.next();

        System.out.println("退出主线程：" + Thread.currentThread().getName());
    }
}
